package com.newly.center.sys.auth;

import com.newly.common.base.constants.AuthConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

/**
 * oauth2授权服务器
 *
 * @author: guan
 * @date: 2021/06/20/2:09
 */
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private TokenStore tokenStore;

    @Autowired
    private JwtAccessTokenConverter jwtAccessTokenConverter;

    /**
     * 配置授权方式
     */
    /*
        http://localhost:9090/oauth/authorize?response_type=password&client_id=newly-system
        &redirect_uri=http://www.baidu.com&scope=all
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient(AuthConstant.OAUTH2_CLIENT_ID)
                .secret(passwordEncoder.encode(AuthConstant.OAUTH2_SECRET_ID))
                .scopes(AuthConstant.OAUTH2_SCOPES)
                .authorizedGrantTypes(AuthConstant.OAUTH2_GRANT_TYPE)
                .redirectUris(AuthConstant.OAUTH2_REDIRECT_URLS)
                .accessTokenValiditySeconds(AuthConstant.OAUTH2_EXPIRE_TIME);
    }


    /**
     * 暴露服务
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenStore(tokenStore)
                .authenticationManager(authenticationManager)
                .accessTokenConverter(jwtAccessTokenConverter);
    }
}
